﻿using System;
using System.IO;
using System.Net;
using System.Text;
using System.Web.Mvc;
using TSharp.Core.AppBox.Perfmon;

namespace TSharp.Core.AppBox.Controllers
{
    public class TestController : AsyncController
    {

        //  [AsyncTimeout(5000)] // 設定Action的逾期時間為5秒鐘   
        [NoAsyncTimeout]
        public void IndexAsync(string url)
        {
            AsyncManager.OutstandingOperations.Increment(1);
            if (string.IsNullOrEmpty(url))
                url = "http://www.asp.net/";
            WebRequest req = HttpWebRequest.Create(url);
            var p = new WebProxy();
            //p.Address = new System.Uri("http://firewall.jiuqi.com.cn:8080");
            //p.Credentials = new NetworkCredential("tangjingbo", "tjb@123");
            req.Proxy = p;
            req.BeginGetResponse((ar) =>
            {
                try
                {
                    WebResponse response = req.EndGetResponse(ar);
                    var html = DecodeData(response);
                    AsyncManager.Parameters["html"] = html;
                    AsyncManager.OutstandingOperations.Decrement();
                }
                catch (System.Exception ex)
                {
                    AsyncManager.Parameters["html"] = ex.ToString();
                    AsyncManager.OutstandingOperations.Decrement();
                }
            }, null);
        }
        private string DecodeData(WebResponse w)
        {
            //    WebRequest r = WebRequest.Create(Url);
            //    WebResponse w = r.GetResponse();
            //            
            //     first     see     if     content     length     header     has     charset     =     calue            
            //            
            String charset = string.Empty;
            String ctype = w.Headers["content-type"];
            if (ctype != null)
            {
                int ind = ctype.IndexOf("charset=");
                if (ind != -1)
                {
                    charset = ctype.Substring(ind + 8);
                }
            }
            //     save     data     to     a     memorystream            
            MemoryStream rawdata = new MemoryStream();
            byte[] buffer = new byte[1024];
            Stream rs = w.GetResponseStream();
            int read = rs.Read(buffer, 0, buffer.Length);
            while (read > 0)
            {
                rawdata.Write(buffer, 0, read);
                read = rs.Read(buffer, 0, buffer.Length);
            }
            rs.Close();
            //            
            //     if     ContentType     is     null,     or     did     not     contain     charset,     we     search     in     body            
            //            
            if (charset == null)
            {
                MemoryStream ms = rawdata;
                ms.Seek(0, SeekOrigin.Begin);
                StreamReader srr = new StreamReader(ms, Encoding.ASCII);
                String meta = srr.ReadToEnd();
                if (meta != null)
                {
                    int start_ind = meta.IndexOf("charset=");
                    int end_ind = -1;
                    if (start_ind != -1)
                    {
                        end_ind = meta.IndexOf("\"", start_ind);
                        if (end_ind != -1)
                        {
                            int start = start_ind + 8;
                            charset = meta.Substring(start, end_ind - start + 1);
                            charset = charset.TrimEnd(new Char[] { '>', '"' });
                        }
                    }
                }
            }
            var encoding = charset != string.Empty ? Encoding.GetEncoding(charset.ToUpper()) : Encoding.Default; ;
            rawdata.Position = 0;

            using (var sr = new StreamReader(rawdata, encoding))
            {
                return sr.ReadToEnd();
            }
        }
        public ActionResult IndexCompleted(string html)
        {
            return View((object)html);
        }

        public ActionResult Config()
        {
            return View(QPerfMonFile.Instance);
        }
        [HttpPost]
        public ActionResult Config(QPerfMonFile obj)
        {

            return View(obj);
        }
    }
}
